<template>
  <div class="pad-20 bgc-default">
    <div class="pad-20 bg-color-white">
      <div>
        <el-button @click="handleAddGroup" type="primary">添加商品组</el-button>
      </div>
      <!--顶部搜索 -->
      <div class="top-operate-default mar-t-20">
        <div class="search-item">
          <label>搜索商品组：</label>
          <el-input @keyup.enter.native="handleSearch" v-model.trim="searchListQuery.goodsGroupName" placeholder="请输入商品组名称"></el-input>
          <el-button-group class="mar-l-20">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button plain @click="resetSearch">重置</el-button>
          </el-button-group>
        </div>
      </div>

      <div class="pad-t-15 pad-b-15 font-14 v-align-c">
        <el-checkbox class="mar-l-14 mar-r-0" v-model="allChecked" @change="selectAll"><span class="mar-l-20">当页全选</span></el-checkbox>
        <span class="pad-l-4 pad-r-4">|</span>
        <div class="width-80">已选{{multipleSelection.length}}项</div>
        <el-button @click="handleDelete">批量删除</el-button>
      </div>
      <!-- 内容列表 -->
      <div class="table-container">
        <el-table ref="multipleTable" :data="groupList" @selection-change="handleSelectionChange" v-loading="listLoading" element-loading-text="加载中">
          <el-table-column width="50px" type="selection"></el-table-column>
          <el-table-column label="商品组名称" min-width="300px" prop="goodsGroupName" fixed="left">
            <template slot-scope="scope">
              <div @click="handleEditGroup(scope.row)" class="cursor-p" style="color:#155bd4;">
                {{scope.row.goodsGroupName}}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="商品数" min-width="200px" align="left">
            <template slot-scope="scope">
              <div>
                共{{scope.row.detailList.length}}件商品
              </div>
            </template>
          </el-table-column>
          <el-table-column min-width="200px" label="操作" align="right" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" size="medium" @click="handleEditGroup(scope.row)">编辑</el-button>
              <el-button type="text" size="medium" @click="handleDetail(scope.row)">商品明细</el-button>
              <el-popconfirm
                title="您确定删除吗？"
                @onConfirm="handleDelete(scope.row)"
              >
                <el-button slot="reference" class="mar-l-10" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 列表分页 -->
      <div class="pagination">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="searchListQuery.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="searchListQuery.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </div>

    <el-dialog :title="groupTitle" v-el-drag-dialog :visible.sync="goodsGroupVisible" :close-on-press-escape="true" :center="true" width="600px">
      <el-form ref="goodsGroupForm" :model="goodsGroupForm" label-position="right" :rules="rules" label-width="120px">
          <el-form-item label="商品组名称" prop="goodsGroupName" >
          <el-input v-model="goodsGroupForm.goodsGroupName" class="width-per-70" placeholder="请输入商品组名称"></el-input><br/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="goodsGroupVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveGroup">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="选择批发商品" :visible.sync="selectGoodsVisible" :close-on-press-escape="true" :center="true" width="1200px">
      <div class="scroll-layer-box">
        <goods-select :groupType="2" :groupObj="selectedGroupObj" :showFlag="selectGoodsVisible" @saveDetail="saveGoodDetailCallBack"></goods-select>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import goodsSelect from '../components/goods-select'
  import warehouseSelect from '../components/warehouse-select'
  import elDragDialog from '@/directive/el-dragDialog'
  import { listSupplier } from '@/api/user/supplier'
  import { pageGoodsGroup, saveGoodsGroup, deleteGroup } from '@/api/goods/goodsGroup'

  export default {
    components: { goodsSelect, warehouseSelect },
    directives: {
      elDragDialog
    },
    data() {
      return {
        total: null,
        listLoading: true,
        goodsGroupVisible: false,
        selectGoodsVisible: false,
        supplierVisible: false,
        groupList: [],
        supplierList: [],
        multipleSelection: [],
        // 商品组标题
        groupTitle: '',
        // 选中商品组对象
        selectedGroupObj: '',
        // 查询表单
        searchListQuery: {
          currentPage: 1,
          size: 10,
          enterpriseId: this.getEnterpriseId(),
          goodsGroupName: '',
          goodsGroupType: '',
          groupType: 2
        },
        // 商品组表单
        goodsGroupForm: {
          goodsGroupId: '',
          goodsGroupName: '',
          goodsGroupType: '',
          supplierId: ''
        },
        rules: {
          goodsGroupName: [
            { required: true, message: '请输入商品组名称', trigger: 'blur' }
          ]
        },
        allChecked: false,
        selectWarehouseVisible: false
      }
    },
    // 初始化页面
    created() {
      this.initList()
      listSupplier({ enterpriseId: this.getEnterpriseId() }).then(response => {
        if (response.isError) return
        this.supplierList = response.data
      })
    },
    mounted() {
    },
    methods: {
      // 初始化
      initList(parameters) {
        this.listLoading = true
        pageGoodsGroup(this.searchListQuery).then(response => {
          if (response.isError) return
          this.groupList = response.data.records
          this.total = response.data.total
          this.listLoading = false
        })
      },
      // 勾选事件
      handleSelectionChange(val) {
        this.multipleSelection = val
        if (this.multipleSelection.length === this.groupList.length) {
          this.allChecked = true
        } else {
          this.allChecked = false
        }
      },
      // 查询事件
      handleSearch() {
        this.searchListQuery.currentPage = 1
        this.initList()
      },
      // 重置事件
      resetSearch() {
        this.searchListQuery = {
          currentPage: 1,
          size: 10,
          enterpriseId: this.getEnterpriseId(),
          goodsGroupName: '',
          groupType: 2
        }
        this.initList()
      },
      // 商品组保存事件
      handleSaveGroup() {
        this.$refs['goodsGroupForm'].validate((valid) => {
          if (valid) {
            var form = {
              enterpriseId: this.getEnterpriseId(),
              goodsGroupId: this.goodsGroupForm.goodsGroupId,
              goodsGroupName: this.goodsGroupForm.goodsGroupName,
              groupType: this.searchListQuery.groupType
            }
            saveGoodsGroup(form).then((response) => {
              if (response.isError) return
              this.$message({ type: 'success', message: '保存成功!' })
              this.goodsGroupVisible = false
              this.initList()
            })
          }
        })
      },
      // 新增事件
      handleAddGroup() {
        this.groupTitle = '新增商品组'
        this.goodsGroupForm = {
          goodsGroupId: '',
          goodsGroupName: ''
        }
        if (this.$refs['goodsGroupForm']) this.$refs['goodsGroupForm'].resetFields()
        this.goodsGroupVisible = true
      },
      // 编辑事件
      handleEditGroup(row) {
        this.groupTitle = '编辑商品组'
        if (this.$refs['goodsGroupForm']) this.$refs['goodsGroupForm'].resetFields()
        Object.assign(this.goodsGroupForm, row)
        this.goodsGroupVisible = true
      },
      // 删除事件（校验）
      handleDelete(row) {
        var ids = []
        var dupCheck = false
        var dupCheckMsg = ''
        if (row.goodsGroupId) {
          ids.push(row.goodsGroupId)
          dupCheck = row.detailList.length > 0
          dupCheckMsg = row.goodsGroupName
        } else {
          this.multipleSelection.forEach(o => {
            ids.push(o.goodsGroupId)
            if (!dupCheck) {
              dupCheck = o.detailList.length > 0
              dupCheckMsg = o.goodsGroupName
            }
          })
        }
        if (ids.length === 0) {
          this.$message({ message: '暂无商品组', type: 'warning' })
          return
        }
        this.$confirm('商品组删除后不可恢复，确定要删除？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (dupCheck) {
            this.$message({ message: dupCheckMsg + '商品组下存在商品无法删除', type: 'warning' })
            return
          } else {
            this.doDelete(ids)
          }
        }).catch(() => {
        })
      },
      // 删除事件
      doDelete(ids) {
        deleteGroup({ goodsGroupIds: ids }).then(response => {
          if (response.isError) return
          this.$message({ type: 'success', message: '删除成功!' })
          this.initList()
        })
      },
      // 商品明细链接事件
      handleDetail(row) {
        var self = this
        self.selectedGroupObj = Object.assign({}, row)
        self.selectGoodsVisible = true
      },
      // 商品明细回调事件
      saveGoodDetailCallBack(refreshFlag) {
        this.selectGoodsVisible = false
        if (refreshFlag) this.initList()
      },
      // 更改当前页数
      handleCurrentChange(val) {
        this.searchListQuery.currentPage = val
        this.initList()
      },
      // 更改当前页面大小
      handleSizeChange(val) {
        this.searchListQuery.size = val
        this.initList()
      },
      selectAll() {
        if (this.multipleSelection.length === 0 || this.multipleSelection.length < this.groupList.length) {
          this.groupList.forEach(item => {
            this.$refs.multipleTable.toggleRowSelection(item, true)
          })
        } else {
          this.$refs.multipleTable.clearSelection()
        }
      },
      saveAuthorizeCallBack() {
        this.selectWarehouseVisible = false
      }
    }
  }
</script>
<style lang="less" scoped>
  .top-operate {
    margin-bottom: 0;
    height: 85px;
    background-color: #f7f8fa;
    display: flex;
    align-items: center;
    white-space: nowrap;
    flex-wrap: nowrap;
    width: 100%;
    overflow-x: auto;
  }

  .search-item {
    flex-shrink: 0;
    padding: 0 20px;
    > div,
    .el-cascader {
      margin-right: 0px;
    }
     label{
      font-weight: unset;
    }
    .el-input {
      width: 200px;
    }
  }

  .btn-search {
    height: 60px;
    display: flex;
    align-items: center;
  }
  .table-container{
    /deep/.el-table th > .cell{
      padding-left: 14px;
    }
  }
    .bgc-default {
    /deep/ .el-dialog__body {
      padding-bottom: 140px;
    }
  }
</style>
